<template>
    <view class="login">
        <image class="img" :src="logoUrl" @error="imageError($event)"></image>
        <view class="btn-group">
            <button @getphonenumber="loginHandler" open-type="getPhoneNumber" v-if="agreementChecked">
                手机号快捷登录
            </button>
            <button @click="checkAgreementChecked" v-else>手机号快捷登录</button>
        </view>
        <view class="agreement">
            <view @click="changeHandler">
                <checkbox class="checkbox" color="#FE292B" :checked="agreementChecked" />
            </view>
            <view class="agreement-content">
                <text>我已认真阅读并同意</text>
                <text class="agreement-text" @click="viewAgreementHandler('privacy')">《隐私政策》</text>
                <text class="agreement-text" @click="viewAgreementHandler('service')">《服务协议》</text>
            </view>
        </view>
        <view class="other">
            <view class="title">
                <test class="inner">其他登录方式</test>
            </view>
            <view>
                <view class="mail">
                    <image @click="showModalHandler" :src="getImgOssUrl('/ui-prod-2.7.2/mail.png')"></image>
                </view>
                <view class="sms_login">短信验证登录</view>
            </view>
        </view>
        <uni-popup ref="cupopup" :safe-area="false" :catchtouchmove="false">
            <view class="phone_content">
                <view class="phone_top">
                    <view class="phone_circle">
                        <image :src="logoUrl_small" @error="imageError($event, 1)" class="phone_img" />
                    </view>
                    <text class="phone_title"> {{ tenantName }}</text>
                </view>
                <view class="phone_center">请用您的手机号注册，如您已有我们的会员，我们将自动为您绑定现有会员卡</view>
                <view class="phone_bottom">
                    <view class="phone_form">
                        <label class="phone_label">手机号 +86</label>
                        <input
                            placeholder-class="placeholder"
                            :cursor-spacing="75"
                            placeholder="请输入手机号"
                            type="number"
                            :maxlength="11"
                            v-model="form.mobile" />
                    </view>
                    <view class="phone_form">
                        <label class="phone_label">验证码</label>
                        <input
                            placeholder-class="placeholder"
                            :cursor-spacing="25"
                            type="number"
                            :maxlength="6"
                            placeholder="请输入验证码"
                            v-model="form.smsCode" />
                        <view
                            :class="['phone_code', disabled ? 'phone_disabled' : 'phone_enabled']"
                            @click="sendHandler"
                            >{{ btnText }}</view
                        >
                    </view>
                    <button
                        :class="[btnDisabled ? 'phone_submit_disabled' : 'phone_submit_enabled']"
                        @click="loginMobileHandler">
                        提交
                    </button>
                </view>
            </view>
        </uni-popup>
        <!-- 隐私监听 -->
        <el-privacy-listener-popup></el-privacy-listener-popup>
    </view>
</template>
<script setup>
import { ref, reactive, computed } from 'vue';
import request from '@/request';
import { isNotEmpty, isEmpty, isMobile, getImgOssUrl } from '@/commons/utils';
import storage from '@/commons/storage';
import router from '@/router';
import { onReady } from '@dcloudio/uni-app';
import store from '@/store';
import { loginWxinfoHandler, getParamsBySceneHook } from '@/hooks';
import { getAppId } from '@/commons/utils.js';

const props = defineProps({
    /**活动id */
    luckDrawId: {
        default: '',
        type: [Number, String]
    },
    /**邀请人id */
    inviteMemberId: {
        default: '',
        type: [Number, String]
    },
    channel: {
        default: '',
        type: [Number, String]
    },
    scene: {
        default: '',
        type: [Number, String]
    }
});
const agreementChecked = ref(false);
const cupopup = ref();
let btnText = ref('获取验证码');
const initSecond = 60;
let currentSecond = ref(initSecond);
let intervalId = null;
let logoUrl = ref();
let logoUrl_small = ref();
let tenantName = ref();
const disabled = computed(() => btnText.value !== '获取验证码');
const form = reactive({
    mobile: '',
    smsCode: ''
});
const btnDisabled = computed(() => {
    return isEmpty(form.mobile) || isEmpty(form.smsCode);
});
onReady(() => {
    const useRoute = store.useRouteStore();
    useRoute.lockStatus = false;
    queryLogoUrl();
});

const queryLogoUrl = () => {
    request('shopIdServ')
        .then(res => {
            if (!storage.get('ZW_SHOP_ID')) {
                storage.set('ZW_SHOP_ID', res.data.shopList[0].id);
            }
            logoUrl.value = res.data.tenantInfo.logo;
            logoUrl_small.value = res.data.tenantInfo.logo;
            tenantName.value = res.data.tenantInfo.tenantName;
        })
        .catch(error => {
            uni.showToast({
                title: error.data.msg,
                icon: 'none',
                duration: 3000
            });
        });
};

/**
 * 设置按钮文本
 */
const setNewText = () => {
    btnText.value = `重新获取(${currentSecond.value}秒)`;
    currentSecond.value--;
    if (currentSecond.value === -1) {
        btnText.value = `获取验证码`;
        clearInterval(intervalId);
        currentSecond.value = initSecond;
    }
};

/**
 * 创建倒计时
 */
const createInterval = () => {
    intervalId = setInterval(setNewText, 1000);
};

/**
 * 执行倒计时
 */
const countdownHandler = () => {
    setNewText();
    createInterval();
};

/**
 * 检查手机号
 */
const checkMobileHandler = () => {
    let title;
    const mobile = form.mobile;
    if (isEmpty(mobile)) {
        title = '请先输入手机号';
    } else if (!isMobile(mobile)) {
        title = '请输入正确的手机号';
    }
    if (isNotEmpty(title)) {
        uni.showToast({
            title,
            icon: 'none'
        });
        return false;
    }
    return true;
};

/**
 * 发送短信
 */
const sendHandler = async () => {
    if (!checkMobileHandler()) return;
    if (!disabled.value) {
        const mobile = form.mobile;

        let openid = storage.get('openid');

        if (isEmpty(openid)) {
            const res = await loginWxinfoHandler();
            openid = res.openid;
        }

        request('sendSmsCodeServ', { mobile, openid })
            .then(res => {
                countdownHandler();
            })
            .catch(e => {
                uni.showToast({
                    title: e.data.msg,
                    icon: 'none'
                });
            });
    }
};

/**
 * 用户协议检查
 */
const checkAgreementChecked = () => {
    if (!agreementChecked.value) {
        uni.showToast({
            title: '请先阅读并同意商家协议',
            icon: 'none'
        });
        return false;
    }
    return true;
};

/**
 * 显示弹框
 */
const showModalHandler = () => {
    if (!checkAgreementChecked()) return;
    cupopup.value.open('bottom');
};

/**
 * 手机号自主注册
 */
const loginMobileHandler = () => {
    if (!checkAgreementChecked()) return;
    if (btnDisabled.value) return;
    uni.login({
        success: async res => {
            const loginCode = res.code;
            const shopId = storage.get('ZW_SHOP_ID');
            const { mobile, smsCode } = form;

            const { luckDrawId, inviteMemberId, channel } = props;
            const params = {
                loginCode,
                mobile,
                smsCode,
                shopId,
                channel: Number(channel) || Number(storage.get('channel')),
                inviteMemberId: Number(inviteMemberId) || Number(storage.get('inviteMemberId')),
                luckDrawId: Number(luckDrawId),
                // 游客登陆标识
                userCode: storage.get('userCode') || ''
            };
            const ret = await request('loginSmsServ', params);
            countdownHandler();
            const { token, expireTime, userId, openKid } = ret.data;
            storage.set('token', token);
            storage.set('openKid', openKid);
            storage.set('expireTime', expireTime);
            storage.set('userId', userId);
            storage.remove('channel');
            storage.remove('inviteMemberId');
            router.back();
        }
    });
};

/**
 * 微信授权
 * @param {*} e
 */
const loginHandler = async e => {
    // 当用户资源包额度不足时提示用户
    if (e.detail.errno === 1400001) {
        uni.showToast({ title: '手机号快速验证组件资源包额度不足，请联系客服', icon: 'none' });
        // 手机号快速验证组件调用次数超限通知
        request('notifySms', { appid: getAppId() })
            .then(() => {})
            .catch((err = {}) => {
                const message = err.msg;
                uni.showToast({
                    title: message,
                    icon: 'none',
                    duration: 2000
                });
            });
    } else if (e.detail.errMsg === 'getPhoneNumber:ok') {
        const authorizationCode = e.detail.code;
        uni.login({
            success: async res => {
                const loginCode = res.code;
                const shopId = storage.get('ZW_SHOP_ID');
                const { luckDrawId, inviteMemberId, channel } = props;
                request('loginServ', {
                    loginCode,
                    authorizationCode,
                    grantType: 1,
                    shopId,
                    channel: Number(channel) || Number(storage.get('channel')),
                    inviteMemberId: Number(inviteMemberId) || Number(storage.get('inviteMemberId')),
                    luckDrawId: Number(luckDrawId),
                    // 游客登陆标识
                    userCode: storage.get('userCode') || ''
                })
                    .then(ret => {
                        const { token, expireTime, userId, openKid } = ret.data;
                        storage.set('openKid', openKid);
                        storage.set('token', token);
                        storage.set('expireTime', expireTime);
                        storage.set('userId', userId);
                        storage.remove('channel');
                        storage.remove('inviteMemberId');
                        router.back();
                    })
                    .catch(e => {
                        uni.showToast({
                            title: e.data.msg || '登录失败，请重新登录',
                            icon: 'none',
                            duration: 2000
                        });
                    });
            }
        });
    }
};

/**
 * 同意协议
 */
const changeHandler = () => {
    agreementChecked.value = !agreementChecked.value;
};

/**
 * 查看隐私协议
 * @param {*} type
 */
const viewAgreementHandler = type => {
    const url = '/pages-web/webview/index?type=' + type;
    router.push(url);
};

const imageError = (e, type) => {
    if (type) {
        logoUrl_small.value = getImgOssUrl('/ui-prod-2.0.0/errorImg_small.png');
    } else {
        logoUrl.value = getImgOssUrl('/ui-prod-2.0.0/errorImg.png');
    }
};
</script>
<style lang="scss" src="./style.scss" scoped></style>
